<template>
	<div class="w-full">
		<el-form :inline="true" :model="formInline">
			<el-form-item label="语义类别">
				<el-select
					clearable
					v-model="selectValue"
					value-key="type_id"
					style="width: 180px"
				>
					<el-option
						v-for="item in semanticsOptions"
						:key="item.type_id"
						:label="item.title"
						:value="item"
					>
						<span style="float: left">{{ item.title }}</span>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="关键词类型">
				<el-select
					clearable
					v-model="selectValue1"
					value-key="keyword_type_id"
					style="width: 180px"
				>
					<el-option
						v-for="item in keywordTypeOptions"
						:key="item.keyword_type_id"
						:label="item.keyword_mes"
						:value="item"
					>
						<span style="float: left">{{ item.keyword_mes }}</span>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="关键词">
				<el-input
					v-model="formInline.keyword"
					placeholder="关键词"
					clearable
				></el-input>
			</el-form-item>

			<el-form-item>
				<el-button
					type="primary"
					@click="
						renderData();
						ElMessage.success('查询成功');
					"
					>查询</el-button
				>
				<el-button
					type="success"
					@click="
						initOptions();
						dialogFormVisible = true;
					"
					>新增</el-button
				><el-button
					type="danger"
					@click="
						dataListSelections.length <= 0
							? ElMessage.warning('请至少选中一行')
							: deleteHandle()
					"
					>批量删除</el-button
				>
			</el-form-item>
		</el-form>
		<el-table
			:data="tableData"
			stripe
			style="width: 100%"
			@selection-change="selectionChangeHandle"
		>
			<el-table-column
				fixed
				type="selection"
				header-align="center"
				align="center"
				width="50"
			>
			</el-table-column>
			<el-table-column fixed prop="word" label="语义类别" width="100">
				<template #default="scope">
					<span>{{ filterTypes(scope.row.type_id) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="sentence_nub" label="关键词类型" width="120">
				<template #default="scope">
					<span>{{ filterKeywordType(scope.row) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="sentence_nub" label="关键词" width="80">
				<template #default="scope">
					<span>{{ filterKeyword(scope.row.sqls) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="word" label="语句"> </el-table-column>
			<el-table-column fixed="right" label="操作" width="100">
				<template #default="scope">
					<el-button
						link
						type="warning"
						size="small"
						@click="update(scope.row.sentence_id, scope.row.word)"
						>修改</el-button
					>
					<el-button
						link
						type="danger"
						size="small"
						@click="deleteHandle(scope.row.sentence_id)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<el-affix position="bottom" :offset="60" class="mt-4">
			<el-pagination
				class="mt-2"
				size="small"
				v-model:current-page="formInline.current"
				v-model:page-size="formInline.size"
				:page-sizes="[15, 20, 50, 100]"
				:background="true"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@size-change="renderData"
				@current-change="renderData"
			/>
		</el-affix>
	</div>
	<el-dialog title="添加语句" v-model="dialogFormVisible" :width="dialogWidth">
		<el-form :model="formDialog" label-position="top">
			<el-form-item label="选择分类">
				<el-cascader
					class="m-r-15"
					v-model="cascaderValue"
					:props="props"
					:options="options"
					collapse-tags
					collapse-tags-tooltip
					clearable
					multiple="false"
					@change="handleChange"
					style="width: 100%"
				/>
			</el-form-item>
			<el-form-item label="语句">
				<el-input type="textarea" v-model="formDialog.word"></el-input>
			</el-form-item>
			<el-form-item :label="k" v-for="(k, i) in keywords">
				<el-input v-model="formDialog.keyword['keyword' + i]" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button
					type="primary"
					@click="save"
					:loading="!dialogFormVisible"
					:loading-icon="loading"
					>确 定</el-button
				>
			</div>
		</template>
	</el-dialog>
</template>
<script setup lang="ts">
	useHead({
		title: "语句管理",
	});
	const props: CascaderProps = {
		multiple: true, // 启用多选
		emitPath: true, // 只返回叶子节点的值
		value: "id", // 自定义当前数组的键名 - value
		label: "name", // 自定义当前数组的键名 - label
		children: "children", // 自定义当前数组的键名 - children
		expandTrigger: "hover", // 次级菜单的展开方式 - click/hover
	};

	const current = ref(1);
	const size = ref(15);
	const total = ref(0);

	const selectValue = ref();
	const selectValue1 = ref();
	const formInline = ref({
		current: current.value,
		size: size.value,
		type_id: undefined,
		keyword_type_id: undefined,
		keyword: "",
	});

	const formDialog = reactive({
		word: "",
		keywordIds: [],
		type_id: [],
		keyword: {},
	});
	const dialogFormVisible = ref(false);
	const semanticsOptions = ref([]);
	const keywordTypeOptions = ref([]);
	const options = ref([]);
	//选中值 二维数组
	const cascaderValue = ref<[]>();
	const lastCascaderValue = ref<[]>();
	const tableData = ref([]);
	const keywords = ref([]);
	const dataListSelections = ref([]);
	const filterTypes = (type_id) => {
		let meses = options.value
			.filter((t) => t.id == type_id)
			.map((item) => {
				return item.name;
			});
		return meses[0];
	};
	const filterKeywordType = (row) => {
		let meses = row?.sqls
			.filter((t) => t.keyword)
			.map((item) => {
				return item.keyword_type_id;
			});
		let ktId = meses[0];
		let kname = "";
		let opts = options.value;
		for (var i = 0; i < opts.length; i++) {
			let t = opts[i];
			if (t.id == row.type_id) {
				let child = t.children;
				for (var j = 0; j < child.length; j++) {
					if (child[j].id == ktId) {
						return child[j]?.name;
					}
				}
			}
		}
		return "";
	};
	const filterKeyword = (sqls) => {
		let meses = sqls
			.filter((t) => t.keyword)
			.map((item) => {
				return item.keyword;
			});
		if (meses.length > 0) {
			return meses.join(",");
		}
		return "";
	};
	const selectionChangeHandle = (val) => {
		dataListSelections.value = val;
	};
	const handleChange = (value) => {
		console.log(cascaderValue.value);
		keywords.value = [];
		//子类多选，父类单选逻辑
		if (cascaderValue.value.length !== 0) {
			if (!lastCascaderValue.value) {
				lastCascaderValue.value = cascaderValue.value;
			} else {
				let change = false;
				cascaderValue.value.forEach((c) => {
					if (c[0] !== lastCascaderValue.value[0][0]) {
						change = true;
						return;
					}
				});
				if (change) {
					//分类数变了
					cascaderValue.value = cascaderValue.value.filter(
						(c) => c[0] !== lastCascaderValue.value[0][0]
					);
					lastCascaderValue.value = cascaderValue.value;
				} else {
					//分类数不变
					lastCascaderValue.value = cascaderValue.value;
				}
			}
			//动态关键词逻辑
			let opts = options.value;
			formDialog.keywordIds = [];
			formDialog.keyword = {};
			formDialog.type_id = null;
			keywords.value = null;

			for (var i = 0; i < opts.length; i++) {
				let t = opts[i];
				if (t.id == lastCascaderValue.value[0][0]) {
					keywords.value = t.children
						.filter((c) => {
							let cascaders = lastCascaderValue.value;
							for (var j = 0; j < cascaders.length; j++) {
								if (cascaders[j][1] == c.id) {
									formDialog.keywordIds.push(c.id);
									return true;
								}
							}
						})
						.map((c) => c.name + "(对应关键词)");
					formDialog.type_id = t.id;
					break;
				}
			}
		}
	};
	const selectSemantics = (value: any) => {
		listTree().then((res) => {
			semanticsOptions.value = [];
			if (res.value.error === 0) {
				const { data } = res.value;
				for (var i = 0; i < data.length; i++) {
					let tree = data[i];
					let option = {
						title: tree.title,
						type_id: tree.type_id,
					};
					semanticsOptions.value.push(option);
				}
			}
		});
	};
	const selectKeywordType = (value: any) => {
		listKeyWordType().then((res) => {
			keywordTypeOptions.value = [];
			if (res.value.error === 0) {
				const { data } = res.value;
				for (var i = 0; i < data.length; i++) {
					let tree = data[i];
					let option = {
						keyword_mes: tree.keyword_mes,
						keyword_type_id: tree.keyword_type_id,
					};
					keywordTypeOptions.value.push(option);
				}
			}
		});
	};

	const dialogWidth = ref("300px");
	//挂载页面
	onMounted(() => {
		selectSemantics("");
		selectKeywordType("");
		renderData();
		initOptions();
		window.addEventListener("resize", resizeWindow(dialogWidth));
	});
	//渲染
	const renderData = () => {
		formInline.value.keyword_type_id = selectValue1?.value?.keyword_type_id;
		formInline.value.type_id = selectValue?.value?.type_id;
		pageSentence(formInline.value).then((res) => {
			tableData.value = [];
			if (res.value.error === 0) {
				current.value = res.value.data.current;
				total.value = res.value.data.total;
				tableData.value = res.value.data.records;
			}
		});
	};
	//初始化下拉菜单
	const initOptions = () => {
		groupTree().then((res) => {
			options.value = [];
			if (res.value.error === 0) {
				options.value = res.value.data;
			}
		});
	};

	// 删除
	const deleteHandle = (id) => {
		var ids = id
			? [id]
			: dataListSelections.value.map((item) => {
					return item.sentence_id;
			  });
		ElMessageBox.confirm(
			`确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
			"提示",
			{
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}
		).then(() => {
			deleteSentence({ ids: ids }).then((res) => {
				if (res.value.error === 0) {
					ElMessage.success("删除成功");
					renderData();
				} else {
					ElMessage.error("删除失败");
				}
			});
		});
	};

	const save = (event) => {
		if (!cascaderValue.value || cascaderValue.value.length <= 0) {
			ElMessage.warning("请选择分类！");
			return;
		}
		if (!formDialog.word) {
			ElMessage.warning("请输入语句！");
			return;
		}
		console.log(formDialog);
		saveSentence(formDialog).then((res) => {
			if (res.value.error === 0) {
				ElMessage.success("操作成功");
				dialogFormVisible.value = false;
				renderData();
			} else {
				ElMessage.error(res.value.errorMessage);
			}
		});
	};
	const update = (id, word) => {
		ElMessageBox.prompt("语句", "修改语句", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			inputValue: word,
		})
			.then(({ value }) => {
				if (value) {
					saveSentence({
						sentence_id: id,
						word: value,
					}).then((res) => {
						if (res.value.error === 0) {
							ElMessage({
								type: "success",
								message: "修改成功",
							});
							renderData();
						}
					});
				}
			})
			.catch(() => {
				ElMessage({
					type: "info",
					message: "取消编辑",
				});
			});
	};
</script>
<style></style>